package com.achuna33.Update;

import com.achuna33.Utils.Cache;
import com.achuna33.Utils.HttpRequest;
import com.achuna33.Utils.Response;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.StandardSocketOptions;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import static com.achuna33.Utils.Cache.WriteLogBase;

public class Update extends Thread{
    public Update(){}
    @Override
    public void run(){
        try {
            goUpdate();
        }catch (Exception e){}
    }
    public void goUpdate() throws MalformedURLException {
        WriteLogBase("\n[*]开始下载");
        HttpRequest httpRequest = new HttpRequest("https://github.com/achuna33/MYExploit/blob/master/NewVersionUrl");
        Response response =  httpRequest.Get("");
        if (response.statusCode==0){
            WriteLogBase("\n[*]连接超时");
            return;
        }
        try {
            String url = response.responseBody.split("<td id=\"LC1\" class=\"blob-code blob-code-inner js-file-line\">")[1].split("</td>")[0];
            String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
            path = path.substring(1);
            String localname =path.substring(path.lastIndexOf("/")+1);
            path = path.substring(0,path.lastIndexOf("/"));

            if (System.getProperties().getProperty("os.name").toLowerCase().contains("mac os")){
                path = "/" + path;
            }
            path = java.net.URLDecoder.decode(path,"UTF-8");
            WriteLogBase("\n[*]    下载地址 "+path);
            WriteLogBase("\n[*]    远程地址 "+url);
            String filename =url.substring(url.lastIndexOf("/")+1);
            if (localname.equals(filename)){
                WriteLogBase("\n[*]已经是最新版本了 无需更新");
                return;
            }

            if (download(url,path,filename)){
                WriteLogBase("\n[*]更新成功");
            }else {
                WriteLogBase("\n[*]更新失败 :( 请手动下载");

            }
            System.out.println(url);
            //String path = System.getProperty("java.io.tmpdir") + filename;
            //= path.substring(1);

        }catch (Exception e){
            WriteLogBase("\n[*]下载失败"+"\n"+e.toString());
            return;
        }
    }
    public static String runCmd(String cmd) {

        //WriteLogBase("\n" + cmd);

        String result="";
        try {
            Process ps = Runtime.getRuntime().exec(cmd);
            BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream(), Charset.forName("GBK")));
            String line = null;
            while ((line = br.readLine()) != null) {
               // WriteLogBase(line);
                System.out.println(line);
                result+=line+"\n";
            }
            br.close();
            System.out.println("close ... ");
            ps.waitFor();
            System.out.println("wait over ...");
            return result;
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (InterruptedException e) {

// TODO Auto-generated catch block
            e.printStackTrace();

        }
        System.out.println("child thread donn");
        return null;
    }


    public static void main(String[] args) throws Exception {
        //runCmd("ping -nc 100 baidu.com");
        String url = "https://github.com/achuna33/MYExploit/releases/download/V1.1/MYExploit-1.0-SNAPSHOT.jar";
      System.out.println(url.substring(url.lastIndexOf("/")+1));
      //runCmd("bitsadmin /transfer n https://github.com/achuna33/MYExploit/releases/download/V1.1/MYExploit-1.0-SNAPSHOT.jar");
        download("https://github.com/achuna33/MYExploit/releases/download/V1.1/MYExploit-1.0-SNAPSHOT.jar","C:\\Users\\Chun\\Desktop\\MYExploit","MYExploit-1.0-SNAPSHOT.jar");
    }
    public static boolean download(String urlPath , String targetDirectory,String fileName) throws Exception {
        // 解决url中可能有中文情况
        URL url = new URL(urlPath);
        WriteLogBase("\n[*]下载中.............请等待。");
        HttpsURLConnection http = (HttpsURLConnection)url.openConnection();
        http.setConnectTimeout(8000);
        TrustManager[] trustManagers = {new HttpsTrustManager()};
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, new SecureRandom());
        http.setSSLSocketFactory(context.getSocketFactory());
        http.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        // 设置 User-Agent 避免被拦截
        http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
        String contentType = http.getContentType();
        // 获取文件大小
        long length = http.getContentLengthLong();
        if (length<0){
            WriteLogBase("\n[*] 下载链接时超时 :( ");
        }
        // 获取文件名
        InputStream inputStream = http.getInputStream();
        int total = inputStream.available();


        byte[] buff = new byte[1024*500];

        File file = new File(targetDirectory, fileName);
        if(!file.exists()){
            OutputStream out = new FileOutputStream(file);
            int len ;
            int count = 0; // 计数
            while((len = inputStream.read(buff)) != -1) {
                out.write(buff, 0, len);
                out.flush();
                ++count ;
            }
            // 关闭资源
            out.close();
            inputStream.close();
            http.disconnect();
            WriteLogBase("\n[*] Success :)");
            return true;
        }else{
            WriteLogBase("\n[*] 下载路径下存在同名文件 :(");
        }
        return false;
    }

}
class HttpsTrustManager implements X509TrustManager {

    private static TrustManager[] trustManagers = {new HttpsTrustManager()};

    @Override
    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        // TODO Auto-generated method stub

    }

    @Override
    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        // TODO Auto-generated method stub

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        // TODO Auto-generated method stub
        return null;
    }

    public static void allowAllSSL() {
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
